package club.pinea.handler.lobby;

import club.pinea.annotations.Head;
import club.pinea.interfaces.TCPMessage;
import club.pinea.model.Seat;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.LobbyProto;
import club.pinea.send.MessageSend;
import club.pinea.service.SeatService;
import club.pinea.session.GlobalServerPlayerContainer;
import club.pinea.session.IOSession;
import club.pinea.session.ServerPlayer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 进入房间获取座位信息 类
 * @author: 华上进
 * @createTime: 2021/7/1 9:50
 */
@Head(CommandProto.Command.C_S_ROOM_VALUE)
@Component
public class InRoomHandler implements TCPMessage<BasicProto.BaseMessage> {

    /**
     * redis座位操作服务类
     */
    @Autowired
    private SeatService seatService;


    /**
     * @description: 进入房间获取座位信息 操作方法
     * @author: 华上进
     * @createTime: 2021/7/1 9:25
     */
    @Override
    public void doMessage(BasicProto.BaseMessage msg, IOSession session) throws Exception {
        LobbyProto.RoomRequest request = LobbyProto.RoomRequest.parseFrom(msg.getBody());
        // 更新玩家的room信息
        ServerPlayer serverPlayer = GlobalServerPlayerContainer.getServerPlayer(session);
        serverPlayer.setRoom(request.getRoom());
        //获取当前数据库中有人坐的座位
        List<Seat> seatList = seatService.getRoomSeatDownSeatsByKey(request.getRoom());
        List<LobbyProto.Seat> seats = new ArrayList<>(seatList.size());
        // 循环将数据赋到 protoBuf seats实体
        seatList.forEach(s -> {
            LobbyProto.Seat.Builder seat = LobbyProto.Seat.newBuilder()
                    .setSeatId(s.getSeatId())
                    .setSeatStatus(s.getSeatStatus());
            // 为空则不存
            if (s.getSeatUser() != null) {
                seat.setSeatUser(s.getSeatUser());
            }
            if (s.getDate() != null) {
                seat.setDate(s.getDate());
            }
            seats.add(seat.build());
        });
        // 返回房间实体 和座位实体信息 到客户端
        LobbyProto.RoomResponse response = LobbyProto.RoomResponse.newBuilder()
                .setMultiplyPower(seatList.get(0).getMultiplyPower())
                .addAllSeats(seats)
                .setRes(MessageSend.successRes())
                .build();
        // 返回消息
        MessageSend.sendToUser(response, session);
    }
}
